﻿CREATE FUNCTION QIC.CallFactory_TF(@Token QIC.TokenTable READONLY, @CallerId INT, @CalleeId INT, @ReturnPropertName VARCHAR(50), @TokenMap VARCHAR(50), @Indent INT, @CalleeDelegateName varchar(50))
RETURNS VARCHAR(MAX)
AS
BEGIN

	DECLARE @Call VARCHAR(MAX) 
	DECLARE @TargetMap VARCHAR(MAX)
	DECLARE @SourceMap VARCHAR(MAX)
	DECLARE @LocalToken QIC.TokenTable

	SET @TargetMap = ''

	INSERT INTO @LocalToken (IsOutPut,IsReadOnly,MaxLength,ObjectId,Precision,PropertyId,PropertyName,Scale,UserTypeId)
	SELECT 0,0,0,ObjectId,0,PropertyId,PropertyName,0,0 FROM @Token
	UNION ALL
	SELECT 0,0,0,object_id,0,column_id,name,0,0 FROM sys.columns
	WHERE object_id = @CalleeId


	SELECT @TargetMap += QIC.FormatArg(Targetcolumns.name) + ', '
	FROM sys.columns Targetcolumns
	WHERE Targetcolumns.object_id = @CallerId
	ORDER BY Targetcolumns.column_id

	IF @TargetMap <> '' SET @TargetMap = LEFT(@TargetMap,DATALENGTH(@TargetMap) - 2)
	
	SET @SourceMap = ''
	SELECT @SourceMap += ISNULL(SourceColumns.name, QIC.FormatArg(QIC.TokenSubstitute(@LocalToken, Targetcolumns.name, @TokenMap))) + ', '
	FROM sys.columns Targetcolumns
	LEFT OUTER JOIN sys.columns SourceColumns
		ON SourceColumns.object_id = @CalleeId
		AND QIC.TokenSubstitute(@LocalToken, SourceColumns.name, @TokenMap) =  Targetcolumns.name
	WHERE Targetcolumns.object_id = @CallerId
	ORDER BY Targetcolumns.column_id

	IF @SourceMap <> '' SET @SourceMap = LEFT(@SourceMap,DATALENGTH(@SourceMap) - 2)

	SET @SourceMap = ISNULL(@SourceMap,'')

	SET @Call = ''

	SET @Call += QIC.Indent(@Indent) + 
		'INSERT INTO ' + @ReturnPropertName + '(' + @TargetMap +  ') ' + 
		'SELECT ' + @SourceMap + ' FROM ' + 
		QIC.ObjectName(@CalleeId) +
		' (' + QIC.InterfaceTokenCall(@Token, @CalleeId, @TokenMap) + ')'

	RETURN @Call

END
